<template>
  <el-container class="container">
    <el-header class="reg-header">
      <div class="reg-header-container">
        <div class="reg-title ">欢迎注册</div>
        <div class="fr have-account">
          <el-link type="info" :underline="false">已有账号？</el-link>
          <el-link type="danger" @click="toLoginPage()">请登录<i class="el-icon-arrow-right"></i></el-link>
        </div>
        <div class="clearfix"></div>
      </div>
    </el-header>
    <el-main>
      <div class="reg-main">
        <el-row class="reg-line">
          <el-col :span="24">
            <el-steps :space="2000" :active="step" align-center finish-status="success">
              <el-step title="验证手机"></el-step>
              <el-step title="填写账号信息"></el-step>
              <el-step title="注册成功"></el-step>
            </el-steps>
          </el-col>
        </el-row>
        <el-row v-show="step === 0">
          <el-col :span="24">
            <el-form ref="mobileForm" :model="dataForm" :rules="verifyMobileRules">
              <el-form-item prop="mobile">
                <el-input v-model="dataForm.mobile" placeholder="建议使用常用手机号">
                  <template slot="prepend">手机号</template>
                </el-input>
              </el-form-item>
              <el-form-item prop="captcha">
                <el-col :span="16">
                  <el-input v-model="dataForm.mcaptcha" placeholder="请输入验证码">
                    <template slot="prepend">验证码</template>
                  </el-input>
                </el-col>
                <el-col :span="8">
                  <el-button class="captcha_btn" :disabled="mcaptcha.disabled" @click="acquireMobileCaptcha">{{
                      mcaptcha.title
                  }}</el-button>
                </el-col>
              </el-form-item>
              <el-form-item>
                <el-button class="submit-nextstep-btn" type="danger" @click="collectMobileNextStep(mobileForm)">下一步
                </el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row v-show="step === 1">
          <el-col :span="24">
            <el-form ref="accountForm" label-position="left" :model="dataForm" :rules="verifyAccountRules">
              <el-form-item prop="username">
                <el-input v-model="dataForm.username" placeholder="您的账户名和登录名">
                  <template slot="prepend">用&nbsp;&nbsp;&nbsp;&nbsp;户&nbsp;&nbsp;&nbsp;名</template>
                </el-input>
              </el-form-item>
              <el-form-item prop="pwd">
                <el-input type="password" v-model="dataForm.pwd" placeholder="建议使用两种或两种以上字符组合" autocomplete="off">
                  <template slot="prepend">设&nbsp;置&nbsp;密&nbsp;码</template>
                </el-input>
              </el-form-item>
              <el-form-item prop="rePwd">
                <el-input type="password" v-model="dataForm.rePwd" placeholder="请再次输入密码" autocomplete="off">
                  <template slot="prepend">确&nbsp;认&nbsp;密&nbsp;码</template>
                </el-input>
              </el-form-item>
              <!--              <el-form-item prop="email">
                <el-input v-model="dataForm.email" placeholder="请输入邮箱">
                  <template slot="prepend">邮&nbsp;箱&nbsp;验&nbsp;证</template>
                </el-input>
              </el-form-item>
              <el-form-item prop="ecaptcha">
                <el-col :span="16">
                  <el-input v-model="dataForm.ecaptcha" placeholder="请输入验证码">
                    <template slot="prepend">邮箱验证码</template>
                  </el-input>
                </el-col>
                <el-col :span="8">
                  <el-button class="captcha_btn">获取验证码</el-button>
                </el-col>
              </el-form-item>-->
              <el-form-item>
                <el-button class="submit-nextstep-btn" type="danger" :disabled="submitted"
                  @click="collectAccountNextStep(accountForm)">立即注册</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row v-show="step === 2">
          <el-col :span="24">
            <el-alert title="注册成功" type="success" center show-icon :closable="false"></el-alert>
          </el-col>
        </el-row>
      </div>
    </el-main>
    <el-footer height="auto">
      <bottom />
    </el-footer>
  </el-container>
</template>

<script lang="ts" setup>
import validate from '@/utils/validate';
import { useRouter } from "vue-router";
import http from "@/utils/httpRequest.js";
import { reactive, ref } from 'vue';
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";

import '@/assets/scss/modules/reg.scss';
import Bottom from "@/views/commons/layout/bottom.vue";

const router = useRouter();

// 定义操作步骤
const step = ref(0);

const dataForm = reactive({
  mobile: '',
  mcaptcha: '',
  username: '',
  pwd: '',
  rePwd: '',
  email: '',
  ecaptcha: ''
});

const mcaptcha = reactive({
  disabled: false,
  title: '发送验证码'
});

const submitted = ref(false);

// 验证手机规则
const mobileForm = ref<FormInstance>();

const verifyMobileRules = reactive({
  mobile: [
    {
      validator: async (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error('请输入手机号'));
          return;
        }
        await new Promise((resolve, reject) => {
          http
            .get({
              url: "/auth/mobile-registered",
              data: { 'mobile': value },
            })
            .then(({ data }) => {
              if (http.success(data)) {
                return resolve(data.body);
              } else {
                return resolve('error');
              }
            })
            .catch((error) => {
              return reject(error);
            });
        }).then(res => {
          if (res === 'Y') {
            callback(new Error('该手机号已注册！'));
            return;
          } else if (res === 'error') {
            callback(new Error('验证服务出现异常，请稍后再试！'));
            return;
          }
        })
        callback();
      },
      trigger: 'blur'
    }
  ],
  mcaptcha: [
    {
      validator: async (rule: any, value: any, callback: any) => {
        if (value.trim() === '') {
          callback(new Error('请输入验证码'));
          return;
        }
        await new Promise((resolve, reject) => {
          http
            .post({
              url: "/auth/verify-mcaptcha",
              data: { 'mobile': dataForm.mobile, 'captcha': dataForm.mcaptcha },
            })
            .then(({ data }) => {
              if (http.success(data)) {
                return resolve(data.body);
              } else {
                return resolve('error');
              }
            })
            .catch((error) => {
              return reject(error);
            });
        }).then(res => {
          if (res === '0') {
            callback(new Error('验证码已失效，请重新发送！'));
            return;
          } else if (res === '2') {
            callback(new Error('验证码错误，请重新输入！'));
            return;
          }
        })
        callback();
      },
      trigger: 'blur'
    }
  ]
});

// 获取验证码
const acquireMobileCaptcha = () => {
  http
    .post({
      url: "/auth/send-mcaptcha",
      data: { 'mobile': dataForm.mobile },
    })
    .then(({ data }) => {
      if (http.success(data)) {
        ElMessage.success(data.msg);
        // 验证码倒计时
        let second = 60;
        mcaptcha.disabled = true;
        let task = setInterval(function () {
          mcaptcha.title = `重发验证码（${second}秒）`;
          --second;
          if (second === 0) {
            window.clearInterval(task);
            mcaptcha.title = '发送验证码';
            mcaptcha.disabled = false;
          }
        }, 1000);
      }
    });
};

// 采集移动电话完毕，进行下一步
const collectMobileNextStep = (form: FormInstance | undefined) => {
  if (!form) return;
  form.validate(valid => {
    if (valid) {
      // 跳转下一步
      step.value = 1
    }
  })
};

// 账号信息认证
const accountForm = ref<FormInstance>();

const verifyAccountRules = reactive({
  username: validate.username('用户名'),
  pwd: [
    {
      validator: (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请输入密码'));
          return;
        }
        if (dataForm.rePwd.trim() !== '') {
          accountForm.value.validateField('rePwd', () => { });
        }
        callback();
      },
      trigger: 'blur'
    }
  ],
  rePwd: [
    {
      validator: (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请再次输入密码'));
          return;
        } else if (dataForm.pwd !== dataForm.rePwd) {
          callback(new Error('两次输入密码不一致'));
          return;
        }
        callback();
      },
      trigger: 'blur'
    }
  ],
  email: validate.email(false),
  ecaptcha: [
    {
      validator: (rule, value, callback) => {
        if (dataForm.email.trim() !== '' && dataForm.ecaptcha.trim() === '') {
          callback(new Error('请输入邮箱的验证码'));
          return;
        }
        callback();
      },
      trigger: 'blur'
    }
  ]
});

// 账号信息采集完成，进行下一步
const collectAccountNextStep = (accountForm) => {
  accountForm.validate(valid => {
    if (valid) {
      submitted.value = true
      http.instance({
        url: http.adornUrl('/auth/register'),
        method: 'post',
        data: http.adornData(dataForm)
      }).then(({ data }) => {
        if (http.success(data)) {
          step.value = 2
          return
        }
        submitted.value = false
      })
    }
  })
};

// 跳转登录页面
const toLoginPage = () => {
  router.push({ name: 'login' });
}
</script>
